package com.shawn.db.dao;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.io.File;

/**
 * Created by shawn on 2016/4/10.
 */
public class AddressDao {

    public static String queryAddress(String num,Context context){
        String location = "";
        //1.获取数据库的路径
        File file = new File(context.getFilesDir(),"address.db");
        //2.打开数据库
        //getAbsolutePath : 获取文件的绝对路径
        //factory : 游标工厂
        SQLiteDatabase database = SQLiteDatabase.openDatabase(file.getAbsolutePath(),null,SQLiteDatabase.OPEN_READONLY);
        //3.查询号码归属地
        if (num.matches("^1[34578]\\d{9}$")) {
            String sql = "select location from data2 where id=(select outkey from data1 where id=?)";
            Cursor cursor = database.rawQuery(sql,new String[]{num.substring(0,7)});
            //4.解析cursor
            //因为每个号码对应一个号码归属地,所以查询出来的是一个号码归属地,没有必要用whlie,用if就可以了
            if(cursor.moveToNext()) {
                 location = cursor.getString(0);
            }
            cursor.close();
        }else {
            switch (num.length()) {
                case  3:
                    location = "特殊电话";
                    break;
                case 4:
                    location = "虚拟电话";
                    break;
                case 5:
                    location ="客服电话";
                    break;
                case 7:
                case 8:
                    location="本地电话";
                    break;
                default:
                    if(num.length()>=10 && num.startsWith("0")) {
                        String result = num.substring(1,3);
                        Cursor cursor = database.rawQuery("select location from data2 where area=?",new String[]{result});
                        if(cursor.moveToNext()) {
                            location = cursor.getString(0);
                            location = location.substring(0, location.length()-2);
                            cursor.close();
                        }else {
                            result = num.substring(1,4);
                            cursor = database.rawQuery("select location from data2 where area=?", new String[]{result});
                            if(cursor.moveToNext()) {
                                location = cursor.getString(0);
                                location = location.substring(0,location.length()-2);
                                cursor.close();
                            }
                        }
                    }
                    break;
            }
            database.close();
        }
        return location;
    }
}
